
import axios from 'axios';
// eslint-disable-next-line no-unused-vars
import { Message, Loading } from 'element-ui';
import Cookie from 'js-cookie'
import router from '@/router'
import store from '../store';
// eslint-disable-next-line import/extensions
// const mockDomain = window.conf.domain;

// let loadingNum = 0;   // 请求个数，每个请求是一个loading count;
// let loading;

/* const startLoading = () => {
  if(loadingNum == 0) {
    loading = Loading.service({
      lock: true,
      body: true,
      fullscreen: true,
      text: 'loading...',
      spinner: 'el-icon-loading',
      background: 'rgba(0,0,0,0.5)'
    })
  }
  loadingNum ++;
}

const endLoading = () => {
  loadingNum --;
  if(loadingNum <= 0) {
    loading.close();
  }
} */

const axiosInstance = axios.create(
  {
    // baseURL: process.env.NODE_ENV === 'development' ? `${window.conf.domain}` : `${window.conf.domain}`, // 测试环境地质
    // baseURL: process.env.NODE_ENV === 'development' ? 'http://10.19.151.141:28062' : 'http://10.19.151.141:28062/', // 陈晓冲本地环境
    // timeout: 5000,// // 覆写库的超时默认值现在，在超时前，所有请求都会等待 5 秒
    // withCredentials: true,//表示跨域请求时是否需要使用凭证 false 默认的
    //  baseURL: mockDomain,
    // baseURL: 'http://10.19.151.141:29620',
    headers: {
        'Content-Type': 'application/json', // x-www-form-urlencoded
    },
    timeout: 25000,

  },
);

// POST传参序列化(添加请求拦截器)
axiosInstance.interceptors.request.use((config) => {
  // let allcookie = document.cookie;
  // let token = '', arr = null;
  // if (allcookie) {
  //   arr = allcookie.split(';')
  //   for (let i = 0; i < arr.length; i++) {
  //     if (arr[i].indexOf('token') > -1) {
  //       token = arr[i].split('=')[1]
  //     }
  //   }
  // }
  // console.log(`----`,store.state)
  if (Cookie.get('token')) {
    config.headers.auth = Cookie.get('token');
  } else {
    config.headers.auth = ''
  }
  // console.log('auth',config,'Cookie',Cookie.get('token'));
  // startLoading();
  return config
}, (err) => {
  Message({
    message: '请求错误',
    type: 'error',
    center: true,
    duration: 1000,
    offset: 60,
  });
  return Promise.reject(err)
})

// 返回状态判断(添加响应拦截器)
axiosInstance.interceptors.response.use((response) => response, (err) => {
  // endLoading();
  if (err && err.response) {
    switch (err.response.status) {
      case 400: err.message = '请求错误(400)'; break;
      case 401:
      case 403: {
        err.message = '未授权，请重新登录(401)';
        Message({
          message: err.message,
          type: 'error',
          center: true,
          duration: 1000,
          offset: 60,
          // eslint-disable-next-line
          onClose: () => {
            window.localStorage.setItem('loginInfo', '');
            window.localStorage.setItem('loginToken', '');
            store.commit('menu/SET_MENU', JSON.stringify([]));
            store.commit('menu/SET_LOGIN_INFO', JSON.stringify({}));
            router.replace({
              path: '/login',
            })
          },
        });
        break;
      }
    //  case 403: err.message = '拒绝访问(403)'; break;
      case 404: err.message = '请求出错(404)'; break;
      case 408: err.message = '请求超时(408)'; break;
      case 500: err.message = '服务器错误(500)'; break;
      case 501: err.message = '服务未实现(501)'; break;
      case 502: err.message = '网络错误(502)'; break;
      case 503: err.message = '服务不可用(503)'; break;
      case 504: err.message = '网络超时(504)'; break;
      case 505: err.message = 'HTTP版本不受支持(505)'; break;
      default: err.message = `连接出错(${err.response.status})!`;
    }
  }
  Message({
    message: err.message,
    type: 'error',
    center: true,
    duration: 1000,
    offset: 60,
  });
  return Promise.reject(err)
});

// delete 关键词 所以大写
export const GET = (url, params) => axiosInstance.get(url, { params });
export const POST = (url, data) => axiosInstance.post(url, data);
export const DELETE = (url, data) => axiosInstance.delete(url, { data });
export const PUT = (url, data) => axiosInstance.put(url, data);

export default axiosInstance
